<?php


namespace App\Model;


use App\Tool\Request;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Builder;

/**
 * App\Model\Goods
 *
 * @property int $id
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @property string $name 商品名称
 * @property int $category_id 分类id
 * @property string $img 商品图片，多张，逗号隔开
 * @property int $status 上架状态，1上架，2下架
 * @property int $seller_id 商家id,-1是自营
 * @property \Illuminate\Support\Carbon|null $deleted_at
 * @property string $detail_img 商品详情图，多张，逗号隔开
 * @property int $recommend 推荐商品，1是2否
 * @property-read \App\Model\Category $category
 * @property-read mixed $main_img
 * @property-read mixed|string $min_price
 * @property-read \App\Model\GoodsMode $goods_mode
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Model\GoodsSku[] $goods_sku
 * @method static bool|null forceDelete()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Goods newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Goods newQuery()
 * @method static \Illuminate\Database\Query\Builder|\App\Model\Goods onlyTrashed()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Goods query()
 * @method static bool|null restore()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Goods whereCategoryId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Goods whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Goods whereDeletedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Goods whereDetailImg($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Goods whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Goods whereImg($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Goods whereName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Goods whereRecommend($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Goods whereSellerId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Goods whereStatus($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Goods whereUpdatedAt($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Model\Goods withTrashed()
 * @method static \Illuminate\Database\Query\Builder|\App\Model\Goods withoutTrashed()
 * @mixin \Eloquent
 * @property-read mixed|string $price_interval
 * @property-read int|null $goods_sku_count
 * @property int $view 商品点击数
 * @property-read \App\Model\GoodsCollect|null $collect
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Goods whereView($value)
 */
class Goods extends Base
{

    use SoftDeletes;

    protected $table = 'goods';


    protected $fillable = ['name', 'category_id', 'img', 'status', 'detail_img', 'recommend', 'view'];

    protected $appends = ['main_img', 'min_price', 'price_interval'];


    function setImgAttribute($value)
    {
        if (!$value) return $this->attributes['img'] = '';

        if (!is_array($value)) return $this->attributes['img'] = '';

        return $this->attributes['img'] = join(',', $value);


    }

    function getImgAttribute($value)
    {

        if (!$value) return [];

        return explode(',', $value);

    }


    function getRecommendAttribute($value)
    {


        return (string)$value;
    }

    function getStatusAttribute($value)
    {


        return (string)$value;
    }


    function category()
    {


        return $this->belongsTo(Category::class, 'category_id', 'id');
    }


    function goods_mode()
    {


        return $this->hasOne(GoodsMode::class, 'goods_id', 'id');
    }

    function goods_sku()
    {

        return $this->hasMany(GoodsSku::class, 'goods_id', 'id');
    }

    /**
     * 商品详情
     * Create by Peter
     * 2020/06/01 09:30:01
     * Email:904801074@qq.com
     * @param $id
     * @return array
     */
    static function getDetail($id)
    {

        $re = Goods::with('goods_mode')
            ->with('goods_sku.goods_sku_detail')
            ->with(['goods_sku.snapped_sku.snapped'=>function($query){

                $query->where('disable',1);
            }])
            ->findOrFail($id)->toArray();

        $goods_mode = $re['goods_mode'];

        $sku_name_list = [];

        foreach ($goods_mode['mode'] as $key => $value) {

            $temp = [];

            $temp['sku_name'] = $value;

            $sku_name_list[] = $temp;


        }

        $re['sku_name_list'] = $sku_name_list;

        $sku_list = [];

        foreach ($re['goods_sku'] as $key => $value) {

            $temp = $value;

            foreach ($value['goods_sku_detail'] as $k => $v) {


                $temp['model'][$v['key']] = $v['value'];


            }

            $sku_list[] = $temp;
        }


        $re['sku_list'] = $sku_list;


        return $re;

    }

    function setDetailImgAttribute($value)
    {


        if (!$value) return $this->attributes['detail_img'] = '';

        if (!is_array($value)) return $this->attributes['detail_img'] = '';


        $this->attributes['detail_img'] = join(',', $value);

    }

    function getDetailImgAttribute($value)
    {

        if (!$value) return [];


        return explode(',', $value);

    }

    static function boot()
    {
        parent::boot(); // TODO: Change the autogenerated stub

        //小程序(前端)模块添加必须上架的限制
        static::addGlobalScope('status', function (Builder $builder) {



            $mode=Request::getMode();

            if (strtolower($mode) == strtolower('weapp')) {

                $builder->where('status', 1);
            }

        });
    }


    /**
     * 获取主图
     * Create by Peter
     * 2020/01/15 09:44:30
     * Email:904801074@qq.com
     * @param $value
     * @return mixed|string
     */
    function getMainImgAttribute($value)
    {

        $img = $this->attributes['img'];

        if (!$img) return '';

        $img_list = explode(',', $img);


        return $img_list[0];

    }

    /**
     * 获取最小价格
     * Create by Peter
     * 2019/11/27 17:11:38
     * Email:904801074@qq.com
     * @return mixed|string
     */
    function getMinPriceAttribute()
    {

        $goods_sku = $this->getRelations()['goods_sku'] ?? [];

        if (!$goods_sku) return '暂无报价';

        $goods_sku = $goods_sku->toArray();

        if (!$goods_sku) return '暂无报价';

        $price_list = array_column($goods_sku, 'price');

        return min($price_list);

    }

    /**
     * 获取价格区间
     * Create by PeterYang
     * 2019/12/21 14:40:21
     * Email:904801074@qq.com
     * @return mixed|string
     */
    function getPriceIntervalAttribute()
    {
        $goods_sku = $this->getRelations()['goods_sku'] ?? [];

        if (!$goods_sku) return '暂无报价';

        $goods_sku = $goods_sku->toArray();

//        dd($goods_sku);

        $price_list = array_column($goods_sku, 'price');

        if (!$price_list) return '暂无报价';

        $min = min($price_list);

        $max = max($price_list);

        if ($max == $min) return $max;

        return $min . '-' . $max;

    }


    /**
     * 收藏
     * Create by PeterYang
     * 2020/06/08 22:52:29
     * Email:904801074@qq.com
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    function collect()
    {

        return $this->hasOne(GoodsCollect::class, 'goods_id', 'id');
    }


//    function getRealPriceAttribute()
//    {
//
//        try {
//
//            $relations=$this->getRelation('goods_sku');
//
//            $relations=$relations->toArray();
//
//
//
//
//            dd($relations->toArray());
//
//        }catch (\Exception $exception){
//
//        }
//
//
//
//
//    }

}
